package com.sibbay.syncbox.adapter.box;

import java.io.IOException;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

import com.box.androidlib.BoxSynchronous;
import com.box.androidlib.DAO.BoxFolder;
import com.box.androidlib.ResponseParsers.FolderResponseParser;
import com.box.androidlib.ResponseParsers.UserResponseParser;
import com.sibbay.syncbox.Config;
import com.sibbay.syncbox.adapter.SyncAdapterSynchronous;

public class BoxSyncAdapterSynchronous extends SyncAdapterSynchronous {
	protected static final String TAG = BoxSyncAdapterSynchronous.class.getSimpleName();
	
    // IMPORTANT: Set this to your OpenBox API Key. This demo will not work
    // until you do so!!!
    // To get an API Key, go to https://www.box.net/developers
    static final String CONST_API_KEY = "2celun0c4vegld6pmj7ubup0pc1f6hus";
    static final String CONST_PREFS_FILE_NAME = "prefs_box";
    static final String CONST_PREFS_KEY_AUTH_TOKEN = "AUTH_TOKEN";

    //
	private String mToken;
	private BoxFolder mRemoteRootDirectory;
	private volatile RemoteFileAdaptor mRemoteFileAdaptor;

	public BoxSyncAdapterSynchronous(final Context context) {
		super(context);
	}

	@Override
	public void authenticate() {
		if (Config.DEBUG) 
			Log.d(TAG, "authenticate start");
			
		mAccountName = null;
		mToken = null;
		
        // Check if we have an auth token stored as shared_prefs
        final SharedPreferences prefs = mContext.getSharedPreferences(CONST_PREFS_FILE_NAME, 0);
        final String authToken = prefs.getString(CONST_PREFS_KEY_AUTH_TOKEN, null);
        if (authToken == null) {
            onNotLoggedIn(mContext);
        } else {
    		if (Config.DEBUG) 
    			Log.d(TAG, "authenticate have token:" + authToken);

    		mToken = authToken;
            final BoxSynchronous box = BoxSynchronous.getInstance(CONST_API_KEY);
            try {
            	final UserResponseParser user = box.getAccountInfo(authToken);
            	mAccountName = user.getUser().getEmail();
            	onLoginDone();
			} catch (IOException e) {
				e.printStackTrace();
				onNotLoggedIn(mContext);
			}
        }
	}
    
	@Override
	public RemoteFileAdaptor getRemoteFileAdaptor() {
		if (mRemoteFileAdaptor == null) {
			mRemoteFileAdaptor = new BoxRemoteFileAdapter(BoxSynchronous.getInstance(CONST_API_KEY));
		}
		return mRemoteFileAdaptor;
	}
	
	///
	
	private void onLoginDone() {
		// check root directory and create if need
		mRemoteRootDirectory = checkRootDir(mToken);
	}
	
	private AuthenticationActivity.OnLoginDone mOnLoginDone = new AuthenticationActivity.OnLoginDone() {
		public void done(final String token) {
			if (token != null) {
				// Store auth key in shared preferences.
				// BoxAuthentication activity will set the auth key into the
				final SharedPreferences prefs = mContext.getSharedPreferences(CONST_PREFS_FILE_NAME, 0);
				final SharedPreferences.Editor editor = prefs.edit();
				editor.putString(CONST_PREFS_KEY_AUTH_TOKEN, token);
				editor.commit();
				
				mToken = token;
				Toast.makeText(mContext, "Logged into Box.net", Toast.LENGTH_LONG).show();
				onLoginDone();
			} else {
				mToken = null;
				Toast.makeText(mContext, "Unable to log into Box.net", Toast.LENGTH_LONG).show();
			}
		}
	};
	
	private void onNotLoggedIn(final Context context) {
		if (Config.DEBUG) 
			Log.d(TAG, "onNotLoggedIn");
		
		AuthenticationActivity.sOnLoginDone = mOnLoginDone;
        final Intent intent = new Intent(context, AuthenticationActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
	}
	
	///
	
	private static BoxFolder checkRootDir(final String authToken) {
		if (Config.DEBUG) 
			Log.d(TAG, "checkRootDir token: " + authToken);
		
        final BoxSynchronous box = BoxSynchronous.getInstance(CONST_API_KEY);
        // create root directory
        try {
			final FolderResponseParser dir = box.createFolder(authToken, 0, ROOT_DIRECTORY, false);
			return dir.getFolder();
		} catch (IOException e) {
			e.printStackTrace();
			Log.w(TAG, "createFolder status: " + e);
		}
		return null;
	}
	
	private static final class BoxRemoteFileAdapter implements RemoteFileAdaptor {

		final BoxSynchronous mBox;
		
		BoxRemoteFileAdapter(final BoxSynchronous box) {
			mBox = box;
		}

		@Override
        public boolean isExist(String name) {
	        // TODO Auto-generated method stub
	        return false;
        }

		@Override
        public boolean makeDirectory(String name) {
	        // TODO Auto-generated method stub
	        return false;
        }

		@Override
        public boolean makeFile(String name) {
	        // TODO Auto-generated method stub
	        return false;
        }
	}
}
